package com.yuma.tingshu.user.login;

import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class LoginClient implements ApplicationContextAware {

    private static final Map<Integer, LoginInterface> map = new ConcurrentHashMap<>();

    // 容器会自动调用该方法，传入 ApplicationContext 实例
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 根据注解获取登录的具体策略类对象
        Map<String, Object> beanMap = applicationContext.getBeansWithAnnotation(LoginBean.class);
        if (CollectionUtils.isEmpty(beanMap)) {
            return;
        }
        // 把登录具体策略类对象放入map中
        beanMap.values().forEach(bean -> {
            // 获取bean类上的注解
            LoginBean loginBean = bean.getClass().getAnnotation(LoginBean.class);
            // 获取注解中的value是LoginType对象
            LoginType value = loginBean.value();
            map.put(value.type, (LoginInterface) bean);
        });
    }

    public Map<String, Object> login(Integer type, LoginAccount accout) throws WxErrorException {
        LoginInterface loginInterface = map.get(type);// 获取登录具体策略类对象
        Map<String, Object> login = loginInterface.login(accout);// 调用登录具体策略类对象中的login方法
        return login;
    }
}